import Vue from 'vue'
import Vuex from 'vuex'
import request from '@/common/js/request'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isImport: sessionStorage.getItem('isImport') === 'true',
    userInfo: sessionStorage.getItem('clientUserInfo') ? JSON.parse(sessionStorage.getItem('clientUserInfo')) : null,
    currentStep: sessionStorage.getItem('currentStep') ? parseInt(sessionStorage.getItem('currentStep')) : 0
  },
  mutations: {
    UPDATE_IMPORT_STATUS (state, payload) {
      sessionStorage.setItem('isImport', payload)
      state.isImport = payload
    },
    UPDATE_USERINFO (state, payload) {
      if (payload) {
        sessionStorage.setItem('clientUserInfo', JSON.stringify(payload))
      } else {
        sessionStorage.removeItem('clientUserInfo')
      }
      state.userInfo = payload
    },
    UPDATE_STEP (state, payload) {
      if (payload) {
        sessionStorage.setItem('currentStep', JSON.stringify(payload))
      } else {
        sessionStorage.removeItem('currentStep')
      }
      state.currentStep = payload
    }
  },
  actions: {
    setIsImport ({ commit }, payload) {
      commit('UPDATE_IMPORT_STATUS', payload)
    },
    setUserInfo ({ commit }, payload) {
      commit('UPDATE_USERINFO', payload)
    },
    getStep({ commit, state }, payload) {
      if (state.userInfo.role === 2) {
        request.get('/personal/user/progress').then(res => {
          if (res.status === 1) {
            commit('UPDATE_STEP', res.data)
          }
        })
      }
    }
  },
  getters: {
    isImport (state, getters) {
      return state.isImport
    },
    userInfo (state, getters) {
      return state.userInfo
    },
    currentStep(state, getters) {
      return state.currentStep
    }
  }
})
